package com.glink.manage.ws;

import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chenxx
 */
@ServerEndpoint(value = "/API/Manage/ws/warn/{userId}")
@Service
@Slf4j
public class WarnWebSocketServiceImpl implements WarnWebSocketService {
    private static Map<String, Set<Session>> warnWebSocketMap = new ConcurrentHashMap<>();
    private static final Object locker = new Object();
    private Session session;
    private String userId;
    public static final String TYPE_PONG = "{\"msgType\":\"Pong\"}";
    public static final String PING = "ping";

    @Override
    @OnOpen
    public void onOpen(Session session) {
        try {
            this.session = session;
            Map<String, String> parameters = session.getPathParameters();
            log.info("Current WebSocket connection parameters {}", parameters);
            userId = parameters.get("userId");
//            warnWebSocketSet.add(this);
            if(warnWebSocketMap.containsKey(userId)){
                warnWebSocketMap.get(userId).add(session);
            }else{
                Set<Session>  sessionSet = Sets.newConcurrentHashSet();
                sessionSet.add(session);
                warnWebSocketMap.put(userId, sessionSet);
            }
           
        } catch (Exception e) {
            e.printStackTrace();
            log.error("创建初始会话错误", e);
            try {
                this.session.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
                log.error("关闭会话错误", ioException);
            }
        } finally {
            log.info("新创建连接 userId {} session {}", userId, session);
        }
    }

    @Override
    @OnClose
    public void onClose() {
        log.info("close {}", this.session);
        if(warnWebSocketMap.containsKey(userId)){
            Set<Session> sessionSet = warnWebSocketMap.get(userId);
            if(sessionSet.size() > 1){
                sessionSet.remove(this.session);
            }else{
                warnWebSocketMap.remove(userId);
            }
        }
    }

    @Override
    public Session getSession() {
        return session;
    }

    @Override
    public List<String> getAllUserIds() {
        Set<String> strings = warnWebSocketMap.keySet();
        return new ArrayList<>(strings);
    }

    @Override
    public String getUserId() {
        return userId;
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("the message from client {}", message);
        if (StringUtils.equals(PING, message)) {
            try {
                synchronized (locker) {
                    session.getBasicRemote().sendText(TYPE_PONG);
                }
            } catch (IOException ioException) {
                ioException.printStackTrace();
                log.error("web socket error information 1", ioException);
            }
        }
    }

    @OnError
    public void onError(Throwable t) throws Throwable {
        log.error("websocket 连接异常:", t);
    }

    @Override
    public void sendMessage(String content, List<String> userIdList) {
        log.debug("Websocket data {}", content);
        userIdList.forEach(userId -> {
            synchronized (locker) {
                if(warnWebSocketMap.containsKey(userId)){
                    Set<Session> sessionSet = warnWebSocketMap.get(userId);
                    sessionSet.forEach(session1 -> {
                        try {
                            session1.getBasicRemote().sendText(content);
                        } catch (IOException e) {
                            e.printStackTrace();
                            log.error("web socket error information 1", e);
                        } catch (Exception e) {
                            e.printStackTrace();
                            log.error("web socket error information 2 ", e);
                        }
                        
                    });
                }
            }
        });

    }
}
